﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using DataWinner.Entity.Nba_Sohu.Models;
using DataWinner.Nba.DataAccess.Sohu;
using HtmlAgilityPack;
using JJY.Common;

namespace DataWinner.Business.Manage
{
    public class SohuSpider
    {
        //private const string addressList = "http://data.sports.sohu.com/nba/nba_schedule_by_month.php?season_year=2012";
        //private const string address = "http://data.sports.sohu.com/nba/live_html/nba_live_2012103120.htm";
        private const string sohuAddress = "http://data.sports.sohu.com/nba/";

        public static Dictionary<string, string> FetchMatch(string addressMatchList)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            string strMatchList = HttpUtility.HtmlDecode(HttpRequestHelper.GetHtmlSourceByUrl(addressMatchList, Encoding.Default)
                                .HtmlToString().Trim());

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(strMatchList);

            HtmlNodeCollection matchTrList = doc.DocumentNode.SelectNodes(@"//table[@cellspacing='1']/tr");

            DaTeam daTeam = new DaTeam();
            List<Team_Sohu> teamSet = daTeam.Set.ToList();
            
            DaMatch daMatch = new DaMatch();
            List<Match_Sohu> matchSet = new List<Match_Sohu>();

            DateTime matchDate = System.DateTime.MinValue;
            DateTime matchDateTime = System.DateTime.MinValue;
            foreach (HtmlNode tr in matchTrList)
            {
                HtmlNodeCollection matchTdList = tr.SelectNodes(tr.XPath + "//td");
                if (matchTdList.Count == 9)
                {
                    DateTime tempDate = System.DateTime.MinValue;
                    if (DateTime.TryParse(matchTdList[0].InnerText.Split(' ')[0], out tempDate))
                    {
                        matchDate = tempDate;
                    }
                    else if (matchTdList[0].InnerText.Trim().Length > 0)
                    {
                        continue;
                    }

                    if (DateTime.TryParse(matchDate.ToString("yyyy-MM-dd ") + matchTdList[1].InnerText, out matchDateTime))
                    {
                        Match_Sohu match_Sohu = new Match_Sohu();
                        match_Sohu.MatchTime = matchDateTime;
                        match_Sohu.SeasonYear = matchDate.Month < 9 ? matchDate.Year - 1 : matchDate.Year;
                        match_Sohu.HomeTeamId = GetTeamId(teamSet, matchTdList[2].InnerText);
                        match_Sohu.VisitingTeamId = GetTeamId(teamSet, matchTdList[4].InnerText);
                        match_Sohu.Type = -1;
                        match_Sohu.MatchId = daMatch.CreateMatchId(match_Sohu);
                        matchSet.Add(match_Sohu);

                        if (matchTdList[6].InnerText.IndexOf("比分直播") > 0)
                        {
                            result.Add(match_Sohu.MatchId, sohuAddress + matchTdList[6].SelectNodes(matchTdList[6].XPath + "//a")[2].Attributes["href"].Value.ToString());
                        }
                    }
                }
            }

            daMatch.AddOrModify(matchSet.ToArray());

            return result;
        }

        private static string GetTeamId(List<Team_Sohu> teamSet, string teamName)
        {
            string result = string.Empty;

            DaTeam daTeam = new DaTeam();
            if (teamSet.Any(t => t.TeamName == teamName))
            {
                result = teamSet.FirstOrDefault(t => t.TeamName == teamName).TeamId;
            }
            else
            {
                Team_Sohu teamSohu = new Team_Sohu() { TeamName = teamName };
                daTeam.AddOrModify(teamSohu);
                result = teamSohu.TeamId;
            }

            return result;
        }

        public static bool FetchMatchCourse(Dictionary<string, string> courseAddressSet)
        {
            bool result = true;

            DaMatchCourse daMatchCourse = new DaMatchCourse();

            foreach (KeyValuePair<string, string> item in courseAddressSet)
            {
                try
                {
                    string strMatchCoursePage =
                        HttpUtility.HtmlDecode(HttpRequestHelper.GetHtmlSourceByUrl(item.Value, Encoding.Default)
                        .HtmlToString().Trim());

                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(strMatchCoursePage);

                    HtmlNode nodeTable = doc.DocumentNode.SelectNodes(@"//table[@cellspacing='0']").Last();
                    HtmlNodeCollection nodeTrSet = nodeTable.SelectNodes(nodeTable.XPath + @"//tr");

                    List<MatchCourse_Sohu> courseSet = new List<MatchCourse_Sohu>();
                    short section = 0;
                    int rowIndex = 0;
                    foreach (HtmlNode tr in nodeTrSet)
                    {
                        rowIndex++;
                        HtmlNodeCollection tdSet = tr.SelectNodes(tr.XPath + @"//td");
                        if (tdSet != null)
                        {
                            if (tdSet.Count() == 4)
                            {
                                MatchCourse_Sohu course = new MatchCourse_Sohu();
                                course.MatchId = item.Key;
                                course.RowIndex = rowIndex;
                                course.Section = section;
                                course.Time = DateTime.Parse("00:" + tdSet[0].InnerText);
                                course.HomeDescription = tdSet[1].InnerText;
                                course.HomeScoring = short.Parse(tdSet[2].InnerText.Split('-')[0]);
                                course.VisitingDescription = tdSet[3].InnerText;
                                course.VisitingScoring = short.Parse(tdSet[2].InnerText.Split('-')[1]);

                                courseSet.Add(course);
                            }
                            else if (tdSet.Count() == 1)
                            {
                                if (tdSet[0].InnerText.IndexOf("1") > -1)
                                {
                                    section = 1;
                                }
                                else if (tdSet[0].InnerText.IndexOf("2") > -1)
                                {
                                    section = 2;
                                }
                                else if (tdSet[0].InnerText.IndexOf("3") > -1)
                                {
                                    section = 3;
                                }
                                else if (tdSet[0].InnerText.IndexOf("4") > -1)
                                {
                                    section = 4;
                                }
                            }
                        }
                    }
                    daMatchCourse.AddOrModify(courseSet.ToArray());
                }
                catch (Exception ex)
                {
 
                }
            }

            return result;
        }
    }
}
